package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.TCloudClass;
import model.TStudent;
import model.VBackAdminUser;
import model.VStudent;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import annotation.Log;
import persistent.factory.DAOFactory;
import util.office.NewReadExcel;
import util.office.WriteExcel;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ResponseJSON;

/**
 * 学生管理请求处理类
 * @author xzl
 * @since 2018/10/2 20:25
 */
@Controller 
@RequestMapping(value="/studentmanagement")
public class SysStudentManagementController {

	/**
	 * 添加学生请求控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	//TODO 添加学生请求控制类
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "添加一个学生信息", 
			operationClassPath = "controller.SysTitleManagementController.addStudent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息添加")
	@RequestMapping(value="/addstudent")
	public String addStudent(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		TStudent student=new TStudent();
		
		try {
			String stuid=req.getParameter("stuid");
			String pwd=req.getParameter("pwd");
			String realName=req.getParameter("realName");
			String sex=req.getParameter("sex");
			String birthday=req.getParameter("birthday");
			String classid=req.getParameter("classid");
			String schoolid=req.getParameter("schoolid");
			
			if(stuid!=null && !stuid.equals("") && pwd!=null && !pwd.equals("") && realName!=null && !realName.equals("")
					&& sex!=null && !sex.equals("") && birthday!=null && !birthday.equals("") 
					&& classid!=null && !classid.equals("") && schoolid!=null && !schoolid.equals("")){
				student.setStuid(stuid);
				student.setPwd(pwd);
				student.setRealName(realName);
				student.setSex(sex);
				student.setBirthday(birthday);
				student.setClassid(classid);
				student.setSchoolid(schoolid);
				
				int row=DAOFactory.getStudentDAO().addStudent(student);
				if(row>0){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "学生添加成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "学生添加失败！");
				}
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "学生添加失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code",ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "学生添加失败！");
		}
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 学生信息修改控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 学生信息修改控制类
	@Log(operationType = Constant.OPERTATION_UPDATE, operationDescribe = "修改一个学生信息", 
			operationClassPath = "controller.SysTitleManagementController.updateStudent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息查看")
	@RequestMapping(value="/updatestudent")
	public String updateStudent(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		
		try {
			String id=req.getParameter("id");
			String realName=req.getParameter("realName");
			String sex=req.getParameter("sex");
			String birthday=req.getParameter("birthday");
			
			if(id!=null && !id.equals("") && realName!=null && !realName.equals("")
					&& sex!=null && !sex.equals("") && birthday!=null && !birthday.equals("")){
				TStudent student2=DAOFactory.getStudentDAO().getTStudent(Integer.parseInt(id));
				
				student2.setRealName(realName);
				student2.setSex(sex);
				student2.setBirthday(birthday);
				
				boolean row=DAOFactory.getStudentDAO().updateStudent(student2);
				
				if(row){
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "学生信息修改成功！");
				}else{
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "学生信息修改失败！");
				}
				
			}else{
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "学生信息修改失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", ResponseJSON.FLAG_UNKNOWN_ERORR);
			result.put("msg", "学生信息修改失败！");
		}
		
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 学生信息查询控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 学生信息查询控制类
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "查询学生信息", 
			operationClassPath = "controller.SysTitleManagementController.getStudentByWhere(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息查看")
	@RequestMapping(value="/getstudentwhere")
	public String getStudentByWhere(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		Expression exp=new Expression();
		
		int currentPage = 1;
		int pageSize = 10;
		
		try {
			String schoolid = req.getParameter("schoolid");
			String gradename=req.getParameter("gradename");
			String classid=req.getParameter("classid");
			String idorrelname=req.getParameter("idorrelname");
			
			String page = req.getParameter("page");
			String limit = req.getParameter("limit");
			
			
			if(schoolid!=null && !schoolid.equals("")){
				exp.andEqu("schoolid", schoolid, String.class);
			}
			if(gradename!=null && !gradename.equals("")){
				exp.andEqu("gradename", gradename, String.class);
			}
			if(classid!=null && !classid.equals("")){
				exp.andEqu("classid", classid, String.class);
			}
			if(idorrelname!=null && !idorrelname.equals("")){
				exp.andLeftBraLike("stuid", idorrelname, String.class);
				exp.orRightBraLike("realName", idorrelname, String.class);
			}
			if (page != null && !page.equals("") && limit != null && !limit.equals("")) {
				currentPage = Integer.parseInt(page);
				pageSize = Integer.parseInt(limit);
			}

			String strWhere = exp.toString();
			List<VStudent> list = DAOFactory.getStudentDAO().getStudentListBywhere(strWhere, currentPage, pageSize);
			List<VStudent> listSize = DAOFactory.getStudentDAO().getStudentList(strWhere);
			if (list != null && list.size() > 0) {
				result.put("code", 0);
				result.put("msg", "查询成功");
				result.put("count", listSize.size());
				JSONArray jsonArray = JSONArray.fromObject(list);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "无查询结果");
			}
		} catch (Exception e) {
			result.put("code", 2);
			result.put("msg", "出现未知异常，查询失败");
		}
		PrintWriter out = resp.getWriter();
		out.println(result);
		return null;
	}
	
	/**
	 * 删除学生信息控制类
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 删除学生信息控制类
	@Log(operationType = Constant.OPERTATION_DELETE, operationDescribe = "删除一个学生信息", 
			operationClassPath = "controller.SysTitleManagementController.deleteStudent(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息查看")
	@RequestMapping(value="/deletestudent")
	public String deleteStudent(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result = new JSONObject();
		
		try {
			String stuid = req.getParameter("stuid");
			if (stuid != null && !stuid.equals("")) {
				if (DAOFactory.getStudentDAO().deleteStudent(Integer.parseInt(stuid))) {
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", "删除成功！");
				}
				else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "删除失败，存在外键引用，请删除引用后重试！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "删除失败，学生编号不能为空，请重试！");
			}
			
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "删除失败，存在外键引用，请删除引用后重试！");
			e.printStackTrace();
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * Excel数据导入到数据库(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO Excel数据导入到数据库(2018-12-12 徐震霖)
	@Log(operationType = Constant.OPERTATION_ADD, operationDescribe = "Excel数据导入到数据库", 
			operationClassPath = "controller.SysTitleManagementController.savestuList(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息添加/批量导入")
	@RequestMapping(value="/savestuList")
	public String savestuList(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();

		try {
			List<TStudent> stuList = (List<TStudent>) session.getAttribute("stuList");
			boolean row = DAOFactory.getStudentDAO().batchImport(stuList);
			if (row) {
				result.put("code", 0);
				result.put("msg", "导入成功");
			} else {
				result.put("code", 1);
				result.put("msg", "存在重复数据，导入失败！");
			}
		} catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "出现异常或存在重复数据，导入失败！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 把Excel导入到前台table表格里(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 把Excel导入到前台table表格里(2018-12-12 徐震霖)
	@RequestMapping(value="/excelloadtable")
	public String excelLoadTable(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();

		try {
			List<TStudent> stuList = (List<TStudent>) session.getAttribute("stuList");
			if (stuList != null && stuList.size() > 0) {
				result.put("code", 0);
				result.put("msg", "获取成功！");
				result.put("count", stuList.size());
				JSONArray jsonArray = JSONArray.fromObject(stuList);
				result.element("data", jsonArray);
			} else {
				result.put("code", 1);
				result.put("msg", "获取失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 把Excel转换为List(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @param file
	 * @return
	 * @throws IOException
	 */
	// TODO 把Excel转换为List(2018-12-12 徐震霖)
	@RequestMapping(value="/getexceltablelist")
	public String getExcelTableList(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		NewReadExcel nre = new NewReadExcel();
		List<String> outerList = null;
		//TimeUtil tu = new TimeUtil();
		HttpSession session = req.getSession();
		List<TStudent> stuList = new ArrayList<TStudent>();
		
		try {
			String classid = req.getParameter("classid");
			String schoolid = req.getParameter("schoolid");
			//VCloudUser user = (VCloudUser) session.getAttribute("cloudUser");
			if(classid != null && !classid.equals("")){
				List excelList = nre.readExcel2(req, resp);
				for (int i = 0; i < excelList.size(); i++) {
					outerList = (List<String>) excelList.get(i);
					TStudent student = new TStudent();
					for(int j = 0; j < outerList.size(); j++){					
						switch (j) {
						case 0:
							student.setRealName(outerList.get(j).toString());
							break;
						case 1:
							student.setSex(outerList.get(j).toString());
							break;
						case 2:
							student.setBirthday(outerList.get(j).toString().replace('/','-'));
							break;
						case 3:
							student.setClassid(outerList.get(j).toString());
							break;				
						}						
					}
					student.setClassid(classid);
					student.setSchoolid(schoolid);
					stuList.add(student);
				}
				if (stuList != null && stuList.size() > 0) {
					result.put("code", 0);
					result.put("msg", "获取成功！");
					result.put("count", stuList.size());
					JSONArray jsonArray = JSONArray.fromObject(stuList);
					result.element("data", jsonArray);
					session.setAttribute("stuList", stuList);
				} else {
					result.put("code", 1);
					result.put("msg", "获取失败，请重试！");
				}
			}
			else {
				result.put("code", 1);
				result.put("msg", "班级信息不能为空 ！");
			}
		} 
		catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "出现异常，获取失败，请重试！");
			e.printStackTrace();
		}

		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 学生模板下载(2018-12-12 徐震霖)
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 学生模板下载(2018-12-12 徐震霖)
	@RequestMapping(value="/downloadstudent")
	public String downloadStudent(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result = new JSONObject();
		WriteExcel we = new WriteExcel();
		HttpSession session = req.getSession();
		
		try {
			//后期从session里获取用户信息
			VBackAdminUser user = (VBackAdminUser) session.getAttribute("backUser");
			
			String path = we.studentexportExcel2003("学生信息表模板", "后台管理员下载", user.getUserid().trim());
			if (path != null && !path.equals("")) {
				result.put("code", ResponseJSON.FLAG_SUCC);
				result.put("msg", "获取成功！");
				result.put("path", path);
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "模板下载失败，请重试！");
			}
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "模板下载失败，请重试！");
			e.printStackTrace();
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
	}
	
	/**
	 * 下载学生家长关系信息表模板控制类（基于学生信息）
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO 下载学生家长关系信息表模板控制类（基于学生信息）
	@RequestMapping(value="/downloadstupar")
	public String downloadStuPar(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		HttpSession session = req.getSession();
		WriteExcel we = new WriteExcel();
		Expression exp = new Expression();
		
		try {
			//后期从session里获取用户信息
			VBackAdminUser user = (VBackAdminUser) session.getAttribute("backUser");
			
			String schoolid = req.getParameter("schoolid");
			String userName = req.getParameter("userName");
			String classid = req.getParameter("classid");
			String grade = req.getParameter("grade");			
			String downloadName = "";
			if (classid != null && !classid.equals("") && !classid.equals("00") && !classid.equals("0")) {				
				exp.andEqu("classid", classid, String.class);
				TCloudClass tClass = DAOFactory.getCloudClassDAO().getTClass(classid);				
				if (schoolid != null && !schoolid.equals("") && !schoolid.equals("00") && !schoolid.equals("0")) {
					exp.andEqu("schoolid", schoolid, String.class);
					downloadName += schoolid;
				}
				if (grade != null && !grade.equals("") && !grade.equals("00") && !grade.equals("0")) {
					downloadName += grade;
				}
				downloadName += tClass.getClassName();
				if (userName != null && !userName.equals("")) {
					exp.andLeftBraLike("stuid", userName, String.class);
					exp.orRightBraLike("realName", userName, String.class);
				}
				if (downloadName.equals("")) {
					downloadName = "学生家长关系信息表模板";
				}
				String strWhere = exp.toString();
				List<VStudent> listSize = DAOFactory.getStudentDAO().getStudentList(strWhere);
				if (listSize != null && listSize.size() > 0) {
					JSONArray jsonArray = JSONArray.fromObject(listSize);
					String path = we.exportExcel2003(downloadName, jsonArray, "后台管理员下载", user.getUserid().trim());
					result.put("code", ResponseJSON.FLAG_SUCC);
					result.put("msg", path);
					result.put("ExcelName", downloadName);
					//session.setAttribute("tmpPath", pathlList.get(1));
				} else {
					result.put("code", ResponseJSON.FLAG_FAIL);
					result.put("msg", "未查询到数据！");
				}
			}
			else {
				result.put("code", ResponseJSON.FLAG_FAIL);
				result.put("msg", "班级编号不能为空！");
			}						
		} catch (Exception e) {
			result.put("code", ResponseJSON.FLAG_FAIL);
			result.put("msg", "查询异常，未查询到数据，请重试！");
			e.printStackTrace();
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 根据班级id得到学生信息
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 */
	//TODO  根据班级id得到学生信息
	@Log(operationType = Constant.OPERTATION_QUERY, operationDescribe = "根据班级id得到学生信息", 
			operationClassPath = "controller.SysTitleManagementController.getStudentByClassid(Model model, HttpServletRequest req,HttpServletResponse resp)", 
			operationMenu = "学生管理/学生信息查看")
	@RequestMapping(value="/getstudentbyclassid")
	public String getStudentByClassid(Model model,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");
		
		JSONObject result=new JSONObject();
		Expression ex = new Expression();
		
		String classid = req.getParameter("classid");
		/*String schoolid = req.getParameter("schoolid");
		
		if(schoolid!=null && !schoolid.equals("")){
			ex.andEqu("schoolid", schoolid, String.class);
		}*/
		if (classid != null && !classid.equals("")) {			
			ex.andEqu("classid", classid, String.class);
			String strWhere = ex.toString();
			List<VStudent> stuList1 = DAOFactory.getStudentDAO().getStudentList(strWhere);
			if (stuList1 != null && stuList1.size() > 0) {
				result.put("code", 10001);
				result.put("msg", "获取成功");
				result.put("count", stuList1.size());
				JSONArray jsonArray = JSONArray.fromObject(stuList1);
				result.element("data", jsonArray);
			}
			else {
				result.put("code", 10002);
				result.put("msg", "获取失败");
			}		
		}
		else {
			result.put("code", 10002);
			result.put("msg", "获取失败");
		}
		
		PrintWriter write=resp.getWriter();
		write.print(result);
		return null;
		
	}
	
	/**
	 * 根据班级编号生成学生账号
	 * @param model
	 * @param req
	 * @param resp
	 * @return
	 * @throws IOException
	 * @size 2019-01-10 14:31 徐震霖添加
	 */
	//TODO 根据班级编号生成学生账号
	@RequestMapping(value="/getsyuusername")
	public String getSyuUserName(Model model, HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json");

		JSONObject result = new JSONObject();
		
		try {
			String classid = req.getParameter("classid");
			if (classid != null && !classid.equals("")) {
				String userName = DAOFactory.getStudentDAO().generateStuUserName(classid);
				if (userName != null) {
					result.put("code", 10001);
					result.put("msg", "学生账号生成成功！");
					result.put("stuid", userName);
				}
				else {
					result.put("code", 10002);
					result.put("msg", "出现错误，请重试！");
				}
			}
			else {
				result.put("code", 10002);
				result.put("msg", "班级编号不能为空，请重试！");
			}
		} catch (Exception e) {
			result.put("code", 10002);
			result.put("msg", "出现错误，请重试！");
			e.printStackTrace();
		}
		
		PrintWriter write = resp.getWriter();
		write.print(result);
		return null;
		
	}

	
	
}
